package com.sys.object.common.utils;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 字符串工具集合
 */
@SuppressWarnings("unchecked")
public class MyStringUtils extends org.apache.commons.lang.StringUtils {

	/**
	 * 将字符串用ch分割并放入list
	 * 
	 * @param tags
	 *            被分割字符串
	 * @param ch
	 *            分隔符
	 * @return
	 */
	public static List stringToList(String tags, String ch) {
		if (tags == null)
			return null;
		ArrayList tagList = new ArrayList();
		StringTokenizer st = new StringTokenizer(tags, ch);
		while (st.hasMoreElements()) {
			tagList.add(st.nextToken());
		}
		return tagList;
	}

	/**
	 * 将字符串用空格分割并放入list
	 * 
	 * @param tags
	 *            被分割字符串
	 * @return
	 */
	public static List stringToList(String tags) {
		if (tags == null)
			return null;
		ArrayList tagList = new ArrayList();
		StringTokenizer st = new StringTokenizer(tags);
		while (st.hasMoreElements()) {
			tagList.add(st.nextToken());
		}
		return tagList;
	}

	/**
	 * List转换String
	 * 
	 * @param list
	 *            :需要转换的List
	 * @return String转换后的字符串
	 */
	public static String ListToString(List<?> list) {
		StringBuffer sb = new StringBuffer();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i) == null || list.get(i) == "") {
					continue;
				}
				sb.append(list.get(i));
				sb.append(",");

			}
		}
		return sb.toString();
	}

	/**
	 * HTML输出内容格式转换
	 * 
	 * @param content
	 * @return
	 */
	public static String formatContent(String content) {
		if (content == null)
			return "";
		String randomStr = String.valueOf(System.currentTimeMillis());
		String html = MyStringUtils.replace(content, "&nbsp;", randomStr);
		html = MyStringUtils.replace(html, "&", "&amp;");
		html = MyStringUtils.replace(html, "'", "&apos;");
		html = MyStringUtils.replace(html, "\"", "&quot;");
		html = MyStringUtils.replace(html, "\t", "&nbsp;&nbsp;");// 替换跳格
		html = MyStringUtils.replace(html, " ", "&nbsp;");// 替换空格
		html = MyStringUtils.replace(html, "<", "&lt;");
		html = MyStringUtils.replace(html, ">", "&gt;");
		return MyStringUtils.replace(html, randomStr, "&nbsp;").trim();
	}

	/**
	 * 判断是不是一个合法的电子邮件地址
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		if (email == null)
			return false;
		email = email.trim();
		if (email.indexOf(' ') != -1)
			return false;

		int idx = email.indexOf('@');
		if (idx == -1 || idx == 0 || (idx + 1) == email.length())
			return false;
		if (email.indexOf('@', idx + 1) != -1)
			return false;
		if (email.indexOf('.') == -1)
			return false;
		return true;
		/*
		 * Pattern emailer; if(emailer==null){ String check =
		 * "^([a-z0-9A-Z]+[-|\\._]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		 * emailer = Pattern.compile(check); } Matcher matcher =
		 * emailer.matcher(email); return matcher.matches();
		 */
	}

	/**
	 * 判断字符串是否是一个IP地址
	 * 
	 * @param addr
	 * @return
	 */
	public static boolean isIPAddr(String addr) {
		if (isEmpty(addr))
			return false;
		String[] ips = split(addr, '.');
		if (ips.length != 4)
			return false;
		try {
			int ipa = Integer.parseInt(ips[0]);
			int ipb = Integer.parseInt(ips[1]);
			int ipc = Integer.parseInt(ips[2]);
			int ipd = Integer.parseInt(ips[3]);
			return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0 && ipc <= 255 && ipd >= 0 && ipd <= 255;
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * 二行制转字符串
	 * 
	 * @param b
	 * @return
	 */
	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; b != null && n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}

	public static byte[] hex2byte(byte[] b) {
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("长度不是偶数");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	/**
	 * 将字符串中的某个字符替换成其他字符，例如将aaaabaaa中的b替换成c
	 * 
	 * @param str
	 *            目标字符串
	 * @param src
	 *            将要被替换的字符
	 * @param obj
	 *            被替换成的字符
	 * @return
	 */
	public static String replaceIgnoreCase(String str, String src, String obj) {
		String l_str = str.toLowerCase();
		String l_src = src.toLowerCase();
		int fromIdx = 0;
		StringBuffer result = new StringBuffer();
		do {
			int idx = l_str.indexOf(l_src, fromIdx);
			if (idx == -1)
				break;
			result.append(str.substring(fromIdx, idx));
			result.append(obj);
			fromIdx = idx + src.length();
		} while (true);
		result.append(str.substring(fromIdx));
		return result.toString();
	}

	/**
	 * 用户名必须是数字或者字母的结合
	 * 
	 * @param username
	 * @return
	 */
	public static boolean isLegalUsername(String username) {
		for (int i = 0; i < username.length(); i++) {
			char ch = username.charAt(i);
			if (!isAscii(ch) && ch != '.' && ch != '_' && ch != '-' && ch != '+' && ch != '(' && ch != ')' && ch != '*'
					&& ch != '^' && ch != '@' && ch != '%' && ch != '$' && ch != '#' && ch != '~' && ch != '-')
				return false;
		}
		return true;
	}

	/**
	 * 判断是否是字母和数字的结合
	 * 
	 * @param name
	 * @return
	 */
	public static boolean isAsciiOrDigit(String name) {
		for (int i = 0; i < name.length(); i++) {
			char ch = name.charAt(i);
			if (!isAscii(ch))
				return false;
		}
		return true;
	}

	public static boolean isAscii(char ch) {
		return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9');
	}

	/**
	 * 判断字符串与给定的正则表达式是否匹配
	 */
	public static boolean isMatch(String str, String reg) {
		if (reg != "" && !"".equals(reg)) {
			Pattern p = Pattern.compile(reg);
			Matcher m = p.matcher(str);
			return m.find();
		}
		return false;
	}

	/**
	 * 将字符串转换成16进制
	 */
	public static String toHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return "0x" + str;// 0x表示十六进制
	}

	/**
	 * 将字符串进行base64加密
	 */
	public static String base64Encoder(String str) {
		if (str != null) {
			return (new BASE64Encoder()).encode(str.getBytes()).replaceAll("[\r\n]+", "");
		}
		return null;
	}

	/**
	 * 将加密后的字符串进行base64解码
	 */
	public static String base64Decoder(String bstr) {
		BASE64Decoder decoder = new BASE64Decoder();
		if (bstr != null) {
			try {
				return new String(decoder.decodeBuffer(bstr));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 检验用户昵称是否正确
	 * 
	 * 长度为4-20个字符，由字母、中文、数字、"-"或者"_"组成。
	 */
	public static boolean isValidUsername(String username) {
		String reg = "^[a-zA-Z\u4e00-\u9fa50-9_-]{4,20}$";
		return isMatch(username, reg);
	}

	/**
	 * 检验用户密码是否正确
	 * 
	 * 密码由6-16位半角字符（字母、数字、符号）组成，区分大小写。
	 */
	public static boolean isValidPasswd(String password) {
		String reg = "^[a-zA-Z0-9\\x00-\\xff]{6,16}$";
		return isMatch(password, reg);
	}

	/**
	 * 检验用户输入的手机号是否正确
	 */
	public static boolean isValidMobile(String mobile) {
		String reg = "^(13[0-9]|15[0|1|2|3|5|6|7|8|9]|18[5|6|7|8|9])\\d{8}$";
		return isMatch(mobile, reg);
	}

	/**
	 * 检验用户的qq号是否正确
	 */
	public static boolean isValidQQ(String qq) {
		String reg = "^[1-9][0-9]{4,10}$";
		return isMatch(qq, reg);
	}

	/**
	 * 检验用户的标签是否正确
	 */
	public static boolean isValidTag(String tag) {
		String reg = "^[a-zA-Z\u4e00-\u9fa50-9]{1,14}$";
		return isMatch(tag, reg);
	}

	/**
	 * 验证用户的二级域名是否正确
	 */
	public static boolean isValidSLDN(String name) {
		String reg = "^[a-zA-Z0-9-]{4,20}$";
		return isMatch(name, reg);
	}

	/**
	 * 判断字符串是否是整数
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 验证用户的身份证号码是否合法
	 */
	public static boolean isValidID(String ID) {
		String reg = "^\\d{15}|\\d{18}|\\d{17}X|\\d{17}x$";
		return isMatch(ID, reg);
	}

	/**
	 * 验证用户的真实姓名是否正确
	 */
	public static boolean isValidRealName(String realname) {
		String reg = "^[a-zA-Z\u4e00-\u9fa5]{2,20}$";
		return isMatch(realname, reg);
	}

	/**
	 * 验证用户的分组名称是否正确 分组名称长度为1-10个字符，只能由汉字、字母、数字、符号（-、_）
	 */
	public static boolean isValidGroupName(String groupname) {
		String reg = "^[a-zA-Z\u4e00-\u9fa50-9-_]{1,10}$";
		return isMatch(groupname, reg);
	}

	/**
	 * double转换成字符串
	 * 
	 * @param d
	 * @return
	 */
	public static String convertDouble2Str(double d) {
		StringBuilder result = new StringBuilder();
		DecimalFormat df = new DecimalFormat("0.000");
		String ds = df.format(d);
		result.append(ds.substring(2, 4)).append(".").append(ds.substring(4, 5)).append("%");
		return result.toString();
	}

	public static String decodeUnicode(String theString) {

		char aChar;

		int len = theString.length();

		StringBuffer outBuffer = new StringBuffer(len);

		for (int x = 0; x < len;) {

			aChar = theString.charAt(x++);

			if (aChar == '\\') {

				aChar = theString.charAt(x++);

				if (aChar == 'u') {

					// Read the xxxx

					int value = 0;

					for (int i = 0; i < 4; i++) {

						aChar = theString.charAt(x++);

						switch (aChar) {

						case '0':

						case '1':

						case '2':

						case '3':

						case '4':

						case '5':

						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed   \\uxxxx   encoding.");
						}

					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';

					else if (aChar == 'n')

						aChar = '\n';

					else if (aChar == 'f')

						aChar = '\f';

					outBuffer.append(aChar);

				}

			} else

				outBuffer.append(aChar);

		}

		return outBuffer.toString();

	}

	/**
	 * 根据日期得到数据库表名
	 * 
	 * @return
	 */
	// public static String getTablenameByDate(String date){
	// String[] dateArr = date.split("-");
	// return Constant.TABLE_NAME_PREFIX + dateArr[0]+ "_" +dateArr[1];
	// }

	public static void main(String[] args) {
		// System.out.println(getTablenameByDate("2011-07-18"));
		System.out.println(DigestUtils.md5Hex("123456"));
	}

}